package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.Handle("/", NewLimitHandler(1000, newTestHandler()))
	mux.Handle("/1", NewLimitHandler(1000, newTestHandler1()))
	server := http.Server{
		Addr:         ":8090",
		Handler:      mux,
		ReadTimeout:  20 * time.Second,
		WriteTimeout: 20 * time.Second,
	}

	log.Println(server.ListenAndServe())
}

func NewLimitHandler(maxConns int, handler http.Handler) http.Handler {
	h := &limitHandler{
		connc:   make(chan struct{}, maxConns),
		handler: handler,
	}
	for i := 0; i < maxConns; i++ {
		h.connc <- struct{}{}
	}
	return h
}

func (h *limitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.URL.RequestURI() == "/favicon.ico" {
		return
	}
	fmt.Println("???")
}

type limitHandler struct {
	connc   chan struct{}
	handler http.Handler
}

func newTestHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handler(w, r)
	})
}

func newTestHandler1() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		handler1(w, r)
	})
}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("12321!!")
}

func handler1(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("121232"))
}
